<template>
  <div class="notebook-list">
    <div class="operation-banner">
      <Button @click="showAddNotebookModal" icon="plus" type="ghost">新建笔记本</Button>
      <Modal
        v-model="addNewNotebookModal"
        title="创建笔记本"
        ref="addNewNotebookModalRef"
      >
        <Form ref="addNewNotebookForm" :model="newNotebook" :rules="addNewNotebookRule" inline>
          <FormItem prop="name" class="input-line">
            <Input type="text" v-model="newNotebook.name" placeholder="标题">
              <Icon type="ios-paper" slot="prepend"></Icon>
            </Input>
          </FormItem>
        </Form>
        <div slot="footer">
          <i-button type="primary" size="large" @click="addNewNotebookOk('addNewNotebookForm')">提交</i-button>
          <i-button type="error" size="large" @click="addNewNotebookCancel('addNewNotebookForm')">取消</i-button>
        </div>
      </Modal>
    </div>
    <div class="notebook-list-wrapper">
      <Alert class="note-label">
        笔记本列表 (<span class="list-count">{{ notebookTotal }}</span>)
        <Input v-model="searchNotebookText" @on-change="searchNotebook" class="search-notebook" placeholder="搜索笔记本..."
               style="width: 40%"></Input>
        <Button class="sort-button" type="success" size="small" @click="sortListByNoteCounts">按笔记数量排序</Button>
        <Button type="success" size="small" @click="sortListByUpdate">按笔记更新时间排序</Button>
        <Button type="success" size="small" @click="sortListByCreate">按笔记创建时间排序</Button>
      </Alert>
      <ul class="note-list">
        <transition-group>
          <li @click="changeIDinState(notebook.id)" class="note-item" v-for="notebook in searchedNotebookList"
              :key="notebook.id">
            <div class="icon-name">
              <Icon type="ios-paper"/>
              <span class="note-title">{{ notebook.name }}</span>
              <span class="note-count">{{ notebook.noteNum }}</span>
            </div>
            <div class="date-operation">
              <span class="date">创建时间: {{ _formatData(notebook.createdTime) }}</span>
              <span class="date">更新时间: {{ _formatData(notebook.modifiedTime) }}</span>
              <Button size="small" @click.stop.prevent="doDeleteNotebook(notebook.id, notebook.name)"
                      class="note-delete" type="error">
                删除
              </Button>
              <Button size="small" @click.stop.prevent="showEditNotebookModal(notebook)" class="note-edit"
                      type="success">编辑
              </Button>
              <Modal
                v-model="editNotebookModal"
                title="输入笔记本标题"
                @on-cancel="editNotebookCancel"
                @on-ok="editNotebookOk">
                <Input v-model="editNotebookName" icon="ios-paper"></Input>
              </Modal>
            </div>
          </li>
        </transition-group>
      </ul>
    </div>
  </div>
</template>

<script>
  import {friendlyDate} from '../../common/js/date.js'
  import {getPrincipalInStore} from "../../common/js/auth";

  export default {
    name: 'NotebookList',

    created() {
      console.log('笔记本组件加载中...');
      this.$Loading.start();
      let principal = getPrincipalInStore();
      if (principal) {
        this.$store.commit('changeIsLogin', true);
        this.$store.commit('setUsername', principal.username);
        this.$Loading.finish();
      } else {
        this.$Message.error('没有权限-请先登录');
        this.$router.push('/login');
      }

      // 获取笔记本列表
      this._getNotebookList();
    },

    data() {
      return {
        notebooksList: [],
        searchedNotebookList: [],
        searchNotebookText: '',
        notebookTotal: 0,
        addNewNotebookModal: false,
        editNotebookModal: false,

        newNotebook: {
          name: '',
        },
        addNewNotebookRule: {
          name: [{
            required: true,
            message: '标题不能为空',
            trigger: 'blur'
          }, {
            type: 'string',
            min: 1,
            max: 20,
            message: ' 长度应在1-20之间',
            trigger: 'blur'
          }
          ],
        },

        editNotebookName: '',
        editId: ''
      }
    },

    methods: {
      sortListByNoteCounts() {
        console.log("noteNum sort");
        this.searchedNotebookList.sort();
      },
      sortListByUpdate() {
        console.log("modifiedTime sort");
        this.searchedNotebookList.sort();
      },
      sortListByCreate() {
        console.log("createdTime sort");
        this.searchedNotebookList.sort();
      },
      searchNotebook() {
        if (this.searchNotebookText.length === 0) {
          this.searchedNotebookList = this.notebooksList
        } else {
          let tempNotebookList = [];
          this.notebooksList.forEach(notebook => {
            if (notebook.name.indexOf(this.searchNotebookText) > -1) {
              tempNotebookList.push(notebook)
            }
          });
          this.searchedNotebookList = tempNotebookList
        }
      },
      changeIDinState(notebookId) {
        this.$store.commit('setNotebookId', notebookId);
        this.$store.commit('setNoteId', 1);
        this.$store.commit('setCurrentNote', {});
        this.$router.push(`/note?notebookId=${notebookId}&noteId=1`);
      },
      showAddNotebookModal() {
        console.log(1);
        this.addNewNotebookModal = true
      },
      addNewNotebookOk(model) {
        this.$refs[model].validate(valid => {
          if (valid) {
            this.postJSON(this.$urlApi.SAVE_BOOK, this.newNotebook).then(res => {
              console.log(res);
              // this.notebooksList = res.data;
              // this.notebookTotal = this.notebooksList.length;
              this._getNotebookList();
              this.$refs[model].resetFields();
              this.addNewNotebookModal = false;
            }).catch(err => {
              console.log(err);
            });
          } else {
            return false;
          }
        });
      },
      addNewNotebookCancel(model) {
        this.$refs[model].resetFields();
        this.addNewNotebookModal = false;
      },
      showEditNotebookModal(notebook) {
        this.editId = notebook.id;
        this.editNotebookName = notebook.name;
        this.editNotebookModal = true
      },
      editNotebookOk() {
        let param = {'id': this.editId, 'name': this.editNotebookName};
        this.putRequest(this.$urlApi.UPDATE_BOOK, param).then(res => {
          console.log('update notebook', res);
          this._getNotebookList();
        }).catch(err => {
          console.log(err);
        });
      },
      editNotebookCancel() {
        this.editNotebookName = '';
        this.editNotebookModal = false;
      },
      doDeleteNotebook(bookId, name) {
        this.$Modal.confirm({
          title: `'笔记本【${name}】'`,
          content: '确定要删除此笔记本吗？',
          onOk: () => {
            this.deleteRequest(this.$urlApi.DELETE_BOOK, {'id': bookId}).then(res => {
              console.log(res);
              this._getNotebookList();
            }).catch(err => {
              console.log(err);
            })
          },
        })
      },
      _formatData(dateStr) {
        return friendlyDate(dateStr)
      },
      _getNotebookList() {
        this.postJSON(this.$urlApi.QUERY_BOOK_LIST).then(res => {
          this.notebooksList = res.data;
          this.notebookTotal = this.notebooksList.length;
          this.searchedNotebookList = this.notebooksList;
        }).catch(err => {
          console.log(err);
        });
      },
    },
  }
</script>

<style lang="stylus" scoped>
  @import '../../common/stylus/variables.styl';
  @import '../../common/stylus/styles.styl';

  .sort-button
    margin-left 20px

  .input-line
    width 100%
    margin-bottom 10px

  .notebook-list
    height 100%
    margin-left 100px
    background-color $notebook-bg

    .operation-banner
      border-bottom 1px solid $line-color
      padding 15px

    .notebook-list-wrapper
      width 85%
      margin 20px auto

      .note-label
        font-size 14px

        .search-notebook
          margin-left 20px

        .list-count
          font-weight 700

      .note-list
        font-size 13px
        background-color #fff
        padding 0 15px
        border 1px solid $theme-color
        border-radius 4px
        margin-top 20px
        max-height 400px
        overflow auto

        .note-item
          display flex
          justify-content space-between
          align-items center
          border-bottom 1px solid $line-color
          padding 15px 0
          cursor pointer
          transition all .3s

          &:hover
            color $theme-text-color

          &:last-child
            border-bottom none

          .icon-name
            .note-title
              font-weight 700

            .note-count
              margin-left 10px
              color $date-color
              font-weight 600

          .date-operation
            display flex
            align-items center

            .date
              color $date-color
              margin-right 10px
              font-size 12px

            .note-delete
              margin-right 10px
</style>
